const puppeteer = require("puppeteer");
(async () => {
  let _argv = process.argv;
  if (_argv <= 2) {
    console.log("请指定网址!");
  } else {
    if (!_argv.find(v => v == "-u")) {
      console.log("请指定网址!");
    } else {
      let _time = 3000;
      let _output = "file";
      let _url = process.argv[_argv.findIndex(v => v == "-u") + 1];
      let _width = 1280;
      let _height = 720;
      let _size = "1280x720";
      if (_argv.find(v => v == "-t")) {
        _time = parseInt(process.argv[_argv.findIndex(v => v == "-t") + 1]);
      }
      if (_argv.find(v => v == "-o")) {
        _output = process.argv[_argv.findIndex(v => v == "-o") + 1];
        if (_output !== "base64") {
          _output = "file";
        }
      }
      if (_argv.find(v => v == "-size")) {
        if (process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")) {
          _size =
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[0] +
            "x" +
            parseInt(
              process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[1]
            );
          _width = parseInt(
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[0]
          );
          _height = parseInt(
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[1]
          );
        }
      }
      // 初始化模拟浏览器
      const browser = await puppeteer.launch({
        headless: true
      });
      const page = await browser.newPage();
      // 设置宽高
      await page.setViewport({ width: _width, height: _height });
      try {
        await page.goto(_url);
        await autoScroll(page);
        if (_output == "file") {
          let timestamp = Date.parse(new Date());
          // _url = _url.match(/https:\/\/(\S*)\//)[1];
          await page.screenshot({
            path:
              "output/" + timestamp + "_t" + _time + "_size" + _size + ".jpg",
            fullPage: true
          });
          console.log(
            "生成图片路径为:" +
              __dirname +
              "\\output\\" +
              timestamp +
              "_t" +
              _time +
              "_size" +
              _size +
              ".jpg"
          );
        } else {
          await page
            .screenshot({ encoding: "base64", fullPage: true })
            .then(function(res) {
              console.log("data:image/png;base64," + res);
            });
        }
        setTimeout(function() {
          browser.close();
        }, _time + 1000);
        setTimeout(function() {
          process.exit();
        }, _time + 1100);
      } catch (err) {
        console.log(
          "无法获取的url地址,请确保目标能被访问且使用 http:// 或者 https:// 协议的格式!"
        );
        process.exit();
      }
    }
  }
})();

/**
 * 模拟自动向下滚动
 * @param {object} page
 */
async function autoScroll(page) {
  return page.evaluate(() => {
    return new Promise((resolve, reject) => {
      var totalHeight = 0;
      var distance = 100;
      var timer = setInterval(() => {
        var scrollHeight = document.body.scrollHeight;
        window.scrollBy(0, distance);
        totalHeight += distance;
        if (totalHeight >= scrollHeight) {
          clearInterval(timer);
          resolve();
        }
      }, 100);
    });
  });
}
